<?php

namespace App\Admin\Controllers;

use App\Models\User;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;

class UserController extends AdminController
{
    protected $userTypes = [
        1 => '学生', 2 => '家长'
    ];
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = '用户';


    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new User());

        $userTypes = $this->userTypes;
        $grid->column('id', 'ID');
        $grid->column('name', '姓名');
        $grid->column('email', '邮箱');
        $grid->column('user_type', '用户类型')->display(function ($user_type) use ($userTypes) {
            return $userTypes[$user_type];
        });
        $grid->column('describe', '描述');
        $grid->column('created_at', '创建时间');

        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(User::findOrFail($id));

        $show->field('name', '姓名');
        $show->field('email', '邮箱');
        $show->field('user_type', '用户类型');
        $show->field('created_at', '创建时间');

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new User());

        $form->text('name', '姓名');
        $form->email('email', '邮箱')->rules(function ($form) {
            if ($id = $form->model()->id) {
                return 'nullable|email|unique:users,email,' . $id . ',id';
            } else {
                return 'nullable|email|unique:users,email';
            }
        });
//        $form->password('password', '密码');
        $form->radio('user_type', '用户类型')->options($this->userTypes);
        $form->textarea('describe', '描述')->rows(5);

        return $form;
    }
}
